<template>
  <div class="flex flex-col h-full">
    <SearchContainer is-width @search="getData" @reset="onReset">
      <a-form ref="formRef" class="form-style-flex" :model="formState">
        <a-form-item name="pyjm" label="" class="w-[260px]">
          <a-input v-model:value="formState.pyjm" placeholder="姓名/助记码/卡号/手机号/身份证号" />
        </a-form-item>
        <a-form-item name="dateRange" label="登记时间" class="w-[290px] ml-4">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="就诊事项" class="!w-64 ml-4">
          <a-select v-model:value="formState.dictOutpMatterId" placeholder="请选择" allow-clear>
            <a-select-option v-for="(item, index) in dictOutList" :key="index" :value="item.dictOutpMatterId">{{ item.matterName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="!isArmy" label="关注项目" class="!w-64 ml-4">
          <SelectFocusProject v-model:value="formState.brGzxm" max-tag-count="responsive" multiple />
        </a-form-item>
        <a-form-item name="ghzts" label="状态" class="!w-64 ml-4">
          <a-select v-model:value="formState.ghzts" placeholder="请选择" mode="multiple" :max-tag-count="1">
            <a-select-option value="0">候诊中</a-select-option>
            <a-select-option value="1">已就诊</a-select-option>
            <a-select-option value="2">已退号</a-select-option>
            <a-select-option value="3">已完诊</a-select-option>
            <a-select-option value="4">待回诊</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="医生" class="!w-64 ml-4">
          <SelectTable v-model:value="formState.ghysName" type="医生" page-size="999" @blur="onBlur('ghys')" @select="onSelectEmployee('ghys', $event)" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="业务员" class="!w-64 ml-4">
          <SelectTable v-model:value="formState.brYwyName" type="员工" page-size="999" @blur="onBlur('brYwy')" @select="onSelectEmployee('brYwy', $event)" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="负责人" class="!w-64 ml-4">
          <SelectTable v-model:value="formState.brFzrName" type="员工" page-size="999" @blur="onBlur('brFzr')" @select="onSelectEmployee('brFzr', $event)" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="咨询师" class="!w-64 ml-4">
          <SelectTable
            v-model:value="formState.brZxsName"
            type="员工"
            page-size="999"
            :search-params="{ emplbid: '14' }"
            @blur="onBlur('brZxs')"
            @select="onSelectEmployee('brZxs', $event)"
          />
        </a-form-item>
        <a-form-item label="操作员" class="!w-64 ml-4">
          <SelectTable v-model:value="formState.czyName" type="员工" page-size="999" @blur="onBlur('czy')" @select="onSelectEmployee('czy', $event)" />
        </a-form-item>
        <a-form-item name="ksdm" label="科室" class="!w-64 ml-4">
          <SelectSection v-model:value="formState.ksdm" max-tag-count="responsive" multiple />
        </a-form-item>
        <!-- <a-form-item v-if="isCampus" label="院区" class="w-[240px] ml-4">
          <a-select
            v-model:value="formState.orgCode"
            :options="regionList"
            allow-clear
            :max-tag-count="1"
            mode="multiple"
            :field-names="{ label: 'orgName', value: 'orgCode' }"
            placeholder="请选择"
          />
        </a-form-item> -->
        <a-form-item v-if="!isArmy" label="客户标签" class="w-[260px] ml-2">
          <!-- mode="multiple" -->
          <a-select
            v-model:value="formState.patientLabel"
            :options="tagsList"
            allow-clear
            :max-tag-count="2"
            :field-names="{ label: 'labelName', value: 'id' }"
            placeholder="请选择"
            @change="onSelectLabel"
          />
        </a-form-item>
        <a-form-item v-if="!isArmy" class="w-[250px] ml-2">
          <a-select
            v-model:value="formState.patientLabelList"
            :options="tagsListAll"
            allow-clear
            mode="multiple"
            :max-tag-count="2"
            :field-names="{ label: 'itemName', value: 'id' }"
            placeholder="请选择"
          />
        </a-form-item>
        <a-form v-if="!isArmy" class="form-style-flex">
          <a-form-item label="客户来源" class="w-[300px] ml-3">
            <SelectCustomerSource v-model:value="formState.khly" multiple max-tag-count="responsive" />
          </a-form-item>
          <a-form-item label="挂号类别" class="w-[300px] ml-3">
            <a-select v-model:value="formState.ghlbid" placeholder="请选择" allow-clear>
              <a-select-option v-for="item in categoryList" :key="item" :value="item.ghlbid">{{ item.ghlb }}</a-select-option>
            </a-select>
            <!-- <SelectRegistType v-model:value="formState.ghlbid" trigger="focus" class="w-full" @change="onSelectCategory" /> -->
          </a-form-item>
          <a-form-item name="bah" label="病案号" class="w-64 ml-3">
            <a-input v-model:value="formState.bah" placeholder="病案号" />
          </a-form-item>
          <a-form-item name="czfz" label="初/复诊" class="!w-64 ml-4">
            <a-select v-model:value="formState.czfz" placeholder="请选择" allow-clear>
              <a-select-option value="初诊">初诊</a-select-option>
              <a-select-option value="复诊">复诊</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2 flex-1">
      <div class="flex justify-end mb-2">
        <BaseExport type="门诊" name="登记检索" code="00001022" :search-params="formState">导出</BaseExport>
      </div>
      <BaseTable
        fill
        bordered
        column-code="00001022"
        :loading="loading"
        :extra-height="50"
        :scroll="{ x: 4600 }"
        :data-source="tableData"
        :pagination="{ ...pagination, showTotal: (total) => `共 ${total} 条` }"
        row-key="jzbh"
        :exclude-columns="getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' ? [] : ['chargeStandardName']"
      >
        <!-- , !isCampus ? 'yq' : '' -->
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex == 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex == 'ghztName'">
            <a-tag v-if="record.ghzt === 0" color="blue">候诊中</a-tag>
            <a-tag v-else-if="record.ghzt === 1" color="green">已就诊</a-tag>
            <a-tag v-else-if="record.ghzt === 2" color="red">已退号</a-tag>
            <a-tag v-else-if="record.ghzt === 5" color="orange">未签到</a-tag>
            <a-tag v-else color="green">已完诊</a-tag>
          </template>
          <template v-if="column.dataIndex == 'registerPath'">
            <div>{{ ['窗口', '掌医', '自助机'][record.registerPath] || '-' }}</div>
          </template>
          <template v-if="column.dataIndex === 'brYwyName'">
            <div>{{ record.brYwyName || record.brYwy }}</div>
          </template>
          <template v-if="column.dataIndex == 'brJtdz'">
            <a-tooltip>
              <template #title>{{ record.brJtdz }}</template>
              {{ record.brJtdz }}
            </a-tooltip>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button v-if="!isArmy" type="link" size="small" :disabled="record.ghzt !== 5" @click="onClickSign(record)"> 签到 </a-button>
            <a-button v-if="isMedical && record?.miFilgStr === '自费' && record.ghzt !== 2" type="link" size="small" @click="onOpenMedical(record)"
              >医保登记
            </a-button>
            <BaseButton
              v-if="isMedical && record?.miFilgStr === '医保' && record.ghzt !== 2"
              confirm-text="确认撤销医保登记?"
              type="link"
              size="small"
              danger
              @click="onCancelMedical(record)"
              >撤销医保登记
            </BaseButton>
            <a-button v-authority type="link" size="small" @click="onClickEdit(record)">修改 </a-button>
            <TableMoreButton>
              <BaseButton v-authority confirm-text="确定退号?" type="text" danger size="small" :disabled="record.ghzt !== 0" @click="onHandleReturn(record)">
                退号
              </BaseButton>
              <a-button v-if="!isArmy" type="link" size="small" @click="onPrintLabel(record)"> 标签 </a-button>
              <a-button type="link" size="small" @click="onPrint(record)"> 登记单 </a-button>
              <a-button v-if="!isArmy" v-authority type="link" size="small" @click="onPrintInvoice(record)"> 发票 </a-button>
              <a-button type="link" size="small" @click="onClickReferral(record)">转诊 </a-button>
            </TableMoreButton>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <template v-for="column in columnsData" :key="column.dataIndex">
                <a-table-summary-cell v-if="column.dataIndex === 'xh'"> 合计 </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'zfy'">
                  <div class="text-right">￥{{ formatAmount(summaryData.hjzyf || 0) }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'dpJe'">
                  <div class="text-right">￥{{ formatAmount(summaryData.hjdpJe || 0) }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else />
              </template>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </BaseTable>
    </a-card>
    <Refund
      v-model:open="priceOpen"
      :vip-price="vipPrice"
      :business-data="{ pjhm: billNumber, bcyt: categoryPrice, vipzf: vipPrice, bcyt_st: categoryPrice }"
      :loading-state="loadingState"
      @success="onSuccessPrice"
    />
    <EditModal v-model:open="editOpen" @success="onSuceess" />
    <MovePatientModal v-model:open="referralOpen" :row-data="rowData" @success="onSuceess" />
    <EditInfoModal v-model:open="editInfoOpen" :row-data="rowData" @success="onSuceess" />
    <SignModal v-model:open="signOpen" :row-data="rowData" @success="onSuceess" />
    <MedicalRegistration v-model:open="medicalOpen" :patient-info="rowData" :action-type="actionType" @success="onSuceess" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { formatAmount } from '@/utils/format.js'

import { post } from '@/utils/request'
import SearchContainer from '@/components/SearchContainer'
import { getSystemConfig } from '@/utils/systemConfig'
import SignModal from '@/components/SignModal'
import Refund from '../../components/RefundModal.vue'
import EditModal from './components/EditModal'
import EditInfoModal from './components/EditInfo'
import MovePatientModal from './components/MovePatientModal'
import MedicalRegistration from './components/MedicalRegistration.vue'

const categoryPrice = ref(0)
const isPrint = ref('')
const billNumber = ref('')
const reservationNumber = ref('')
const priceOpen = ref(false)
const editOpen = ref(false)
const referralOpen = ref(false)
const editInfoOpen = ref(false)
const signOpen = ref(false)
const loadingState = ref(false)
const rowData = ref({})
const serialList = ref([])
const dictOutList = ref([])
// const regionList = ref([])
const tagsList = ref([])
const tagsListMany = ref([])
const tagsListAll = ref([])
const summaryData = ref({})
const refundType = ref()
const formRef = ref(null)
const medicalOpen = ref(false)
const actionType = ref(0)
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  ksdm: [],
  brGzxm: [],
  type: '0',
  ghlbid: undefined,
  czfz: undefined
})

const onSelectEmployee = (key, select) => {
  formState.value[key + 'Name'] = select.empName
  formState.value[key] = select.empId
}

const onBlur = (key) => {
  formState.value[key] = ''
}

const onReset = () => {
  formRef.value.resetFields()
  formState.value.brGzxm = []
}
const vipPrice = ref(0)
const onHandleReturn = async (row) => {
  if (row.miFlag === 2) {
    //医保
    rowData.value = row
    medicalOpen.value = true
    actionType.value = 1
  } else {
    //自费
    vipPrice.value = row.vipzf || 0
    const { code, msg, data } = await post('/outp/mzdj/doCancel', { jzbh: row.jzbh, yybh: row.yybh, type: '1' })
    if (code === 0 && data) {
      categoryPrice.value = data.sjdj
      billNumber.value = data.pjhm
      serialList.value = data.dtlsh
      reservationNumber.value = data.yylsh
      refundType.value = data.tflx
      if (data.sjdj) {
        priceOpen.value = true
      } else {
        onSuccessPrice()
      }
    } else {
      if (code !== 0) return message.error(msg || '退号失败')
      message.success('退号成功')
      getData()
    }
  }
}
// getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') === '1' ? '/api/Basic/getOutpRecordInfoList' : '/outp/mzdj/getOutpRecordInfoList'
const { loading, tableData, pagination, getData } = useTable({
  url: '/outp/mzdj/getOutpRecordInfoList',
  immediate: true,
  params: formState.value,
  formatParams: (params) => {
    return {
      ...params,
      stdate: params['dateRange']?.[0],
      eddate: params['dateRange']?.[1]
    }
  },
  formatResult: (result) => {
    if (result && result.length > 0) {
      summaryData.value.hjzyf = result[0].hjzyf
      summaryData.value.hjdpJe = result[0].hjdpJe
    } else {
      summaryData.value = {}
    }
    return result
  }
  // onSuccess: () => {
  //   getSummaryData()
  // }
})
//获取表头
const columnsData = ref([])
const getTableColumns = async () => {
  const { code, data } = await post('/common/util/getTableMappingCloumnList', { id: '00001022' })
  if (code !== 0) return message.error(code)
  columnsData.value = data.filter((item) => {
    if (getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') !== '1' && item.dataIndex === 'chargeStandardName') {
      return false
    } else {
      return !item.isHide
    }
  })
}
// const getSummaryData = async () => {
//   const { code, data } = await post('/outp/mzdj/getOutpRecordInfoListHJ', {
//     ...formState.value,
//     stdate: formState.value.dateRange?.[0],
//     eddate: formState.value.dateRange?.[1]
//   })
//   if (code !== 0) return message.error(code)
//   summaryData.value = data || {}
// }
const onSuceess = () => {
  editOpen.value = false
  referralOpen.value = false
  editInfoOpen.value = false
  getData()
}
const onSuccessPrice = async (params = {}) => {
  loadingState.value = true
  const { code, msg } = await post('/outp/oupCharge/doOutPRefund', {
    pjhm: billNumber.value,
    yylsh: reservationNumber.value,
    ...params,
    tflx: refundType.value,
    lshs: serialList.value,
    type: '1'
  })
  loadingState.value = false
  if (code !== 0) return message.error(msg)
  priceOpen.value = false
  message.success('退号成功')
  getData()
}

// 客户标签
const getTagsList = async () => {
  const { code, data, msg } = await post('/operation/opex/getAllTagsItem', { status: 0 })
  if (code !== 0) return message.error(msg || '获取标签失败')
  tagsList.value = data.map((item) => {
    return {
      labelName: item.labelName,
      id: item.id
    }
  })
  const arr = data
    .map((item) => {
      if (item.children.length > 0) {
        return item.children.map((j) => {
          return {
            id: j.id,
            itemName: j.itemName,
            labelId: j.labelId
          }
        })
      }
    })
    .flat()
  tagsListMany.value = arr.filter((item) => item !== undefined)
}

// 选中客户标签
const onSelectLabel = (id) => {
  formState.value.patientLabelList = []
  const arrAll = tagsListMany.value.map((item) => {
    if (item.labelId === id) {
      return {
        id: item.id,
        itemName: item.itemName
      }
    } else {
      return
    }
  })
  tagsListAll.value = arrAll.filter((item) => item !== undefined)
}
const categoryList = ref([])
// 挂号类别
const getCategoryData = async () => {
  const { code, data } = await post('/operation/opex/getRegisterDictInfoList', {
    mcbh: '',
    pageNum: 1,
    pageSize: 9999,
    requiredDoctor: 0,
    ztflag: 0, // 0有效，1无效
    ghlbid: ''
  })
  if (code === 0) {
    categoryList.value = data
  }
}

// 挂号单打印
const onPrint = async (row) => {
  const { code, msg, data } = await post(isPrint.value, { jzbh: row.jzbh, pjhm: row.pjhm })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 标签打印
const onPrintLabel = async (row) => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', { brId: row.brId })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 发票打印
const onPrintInvoice = async (row) => {
  const { code, msg, data } = await post('/outp/oupCharge/printMedicareChargesFP', { jzbh: row.jzbh, pjhm: row.pjhm })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('OUTP_REGISTER_INVOICE_MODE') === '1') {
    window.open(data)
  } else if (getSystemConfig('OUTP_REGISTER_INVOICE_MODE') === '2') {
    data && window.openExe?.rpt(data)
  }
}

// 转诊
const onClickReferral = async (row) => {
  rowData.value = { ...row }
  referralOpen.value = true
}

// 修改
const onClickEdit = (row) => {
  editInfoOpen.value = true
  rowData.value = { ...row }
}

// 签到
const onClickSign = async (row) => {
  signOpen.value = true
  rowData.value = { ...row }
}
const onOpenMedical = (record) => {
  rowData.value = record
  medicalOpen.value = true
  actionType.value = 0
}

// 获取就诊事项
const getDictOutList = async () => {
  const res = await post('/outp/mzdj/getDictOutpMatterNumberList')
  if (res.code !== 0) return message.error(res.msg)
  dictOutList.value = res.data
  // if (state !== 1) {
  //   visitType.value = res.data[0].dictOutpMatterId
  // }
}
const onCancelMedical = async (record) => {
  const res = await post('/common/patient/doRevocationMedicalInsuranceRegistration', { jzbh: record.jzbh })
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '操作成功')
  getData()
}

// 获取院区  /api/Basic/getPARAMMXBList  入参：{pmlb:'院区'，setbh:'0002'}，出参：{bm:0001,mc:'老园区001'}
// const getRegionList = async () => {
//   const res = await post('/common/emp/getSystemOrganizationList')
//   if (res.code !== 0) return message.error(res.msg)
//   regionList.value = res.data
// }
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
const isMedical = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
// const isCampus = getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') === '1' //启用HIS院区患者信息互联互通
onMounted(async () => {
  // 0：通用|1：上海黑马|2：茗视光
  isPrint.value = getSystemConfig('REGISTRATION_FORM_PRINT_MODE') === '2' ? '/outp/outPrint/getRegistrationPrint' : '/outp/outPrint/getRegistrationBillPrint'
  getDictOutList()
  // isCampus && getRegionList()
  getTagsList()
  getCategoryData()
  getTableColumns()
})
</script>
<style lang="less" scoped>
.ant-picker {
  width: 100%;
}
</style>
